<template>
  <div class="home">
    <!-- 面包屑 -->
    <mbx name1="权限管理" name2="角色列表"></mbx>
    <!-- 卡片区 -->
    <el-card class="mt16">
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        style="margin-left: 15px"
        @click="dialogFormVisible = true"
        >添加用户</el-button
      >
      <!-- 添加按钮 -->
      <!-- 表格 -->
      <el-table :data="user" style="width: 100%">
        <el-table-column type="expand">
          <template #default="scope">
            <div>
              <div v-if="scope.row.children.length > 0">
                <!-- 渲染第一层数据 -->
                <el-row v-for="item in scope.row.children" :key="item.id">
                  <el-col :span="5">
                    <el-tag
                      size="large"
                      type="primary"
                      effect="dark"
                      closable
                      @close="del1(scope.row.id, item.id, scope.row)"
                    >
                      {{ item.authName }}
                    </el-tag>
                  </el-col>
                  <el-col :span="19">
                    <el-row v-for="item1 in item.children" :key="item1.id">
                      <el-col :span="5">
                        <el-tag
                          size="large"
                          type="success"
                          effect="dark"
                          closable
                          @close="del2(scope.row.id, item1.id, scope.row)"
                        >
                          {{ item1.authName }}
                        </el-tag>
                      </el-col>
                      <el-col :span="19">
                        <el-tag
                          size="large"
                          type="warning"
                          effect="dark"
                          closable
                          v-for="item2 in item1.children"
                          :key="item2.id"
                          @close="del3(scope.row.id, item2.id, scope.row)"
                        >
                          {{ item2.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </div>
              <div v-else style="padding: 10px 20px">暂时还没有分配权限哦</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="商品描述" prop="roleDesc"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              @click="edit(scope.row)"
              type="primary"
              size="small"
              :icon="Edit"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="del(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="small"
              :icon="Setting"
              @click="xuroles(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格 -->
      <!-- 模态框 -->
      <el-dialog
        title="添加用户"
        v-model="dialogFormVisible"
        @close="qk"
        width="40%"
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="add"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="form.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="adduser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 模态框 -->
      <!-- 编辑的模态框 -->
      <el-dialog
        title="编辑用户"
        v-model="dialogFormVisible1"
        @close="qk"
        width="40%"
      >
        <el-form
          :model="form1"
          :rules="rules"
          ref="edadd"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form1.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="form1.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="xg">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑的模态框 -->
      <!-- 角色分配的框 -->
      <el-dialog title="分配权限" v-model="dialogFormVisible2" @close="close">
        <!-- default-expanded-keys 默认展开tree组成的数组 -->
        <!-- default-checked-keys 已经选中的tree组成的数组 -->
        <el-tree
          ref="shujuAll"
          :data="tree"
          node-key="id"
          :props="defaultProps"
          default-expand-all
          :default-checked-keys="checkAlltree"
          show-checkbox
        >
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="fpqx">提交</el-button>
        </div>
      </el-dialog>
      <!-- 角色分配的框 -->
    </el-card>
  </div>
</template>

<script>
import { toRefs, reactive, onMounted, ref } from "vue";
import {
  userroles,
  addroles,
  edroles,
  delroles,
  getrights,
  roleshouquan,
  deljues,
} from "../http/api.js";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Delete, Setting } from "@element-plus/icons-vue";
export default {
  setup(props) {
    //   路由
    const router = useRouter();
    const add = ref(null);
    const edadd = ref(null);
    const shujuAll = ref(null);
    const obj = reactive({
      dialogFormVisible: false, //添加弹出框的变量
      dialogFormVisible1: false, //修改弹出框的变量
      dialogFormVisible2: false, //权限弹出框的变量
      user: [], //请求的数据
      form: {
        roleDesc: "",
        roleName: "",
      },
      form1: {
        roleDesc: "",
        roleName: "",
        id: 0,
      },
      rules: {
        roleName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入用户描述", trigger: "blur" },
        ],
      },
      tree: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      checkAlltree: [], //默认选中的tree数组
      jueseid: 0, //角色的id
      checkAlltree1: [], //存放全选和半选的数据
    });
    onMounted(() => {
      getlist();
    });
    //   请求页面中的数据
    const getlist = async () => {
      const res = await userroles();
      console.log("roles", res);
      obj.user = res;
    };
    // 添加用户
    const adduser = () => {
      add.value.validate(async (valid) => {
        if (valid) {
          const res = await addroles(obj.form);
          console.log("这是添加的角色", res);
          obj.dialogFormVisible = false;
          getlist();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    // 清空
    const qk = () => {
      obj.form = {
        roleDesc: "",
        roleName: "",
      };
    };
    //数据回填
    // 编辑
    const edit = (row) => {
      console.log(row);
      obj.dialogFormVisible1 = true;
      obj.form1.roleName = row.roleName;
      obj.form1.roleDesc = row.roleDesc;
      obj.form1.id = row.id;
    };
    const xg = () => {
      edadd.value.validate(async (valid) => {
        if (valid) {
          const res = await edroles(obj.form1);
          console.log("编辑的用户", res);
          obj.dialogFormVisible1 = false;
          getlist();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    // 删除
    const del = (id) => {
      ElMessageBox.confirm("您确定要删除它吗?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        .then(async () => {
          const res = await delroles(id);
          console.log("删除", res);
          getlist();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    // 修改角色权限
    const xuroles = async (row) => {
      console.log("角色权限", row);
      obj.jueseid = row.id;
      console.log("角色id", obj.jueseid);
      const res = await getrights("tree");
      console.log("roles权限", res);
      obj.tree = res;
      shujuhuitan(row, obj.checkAlltree);
      console.log(obj.checkAlltree);
      obj.dialogFormVisible2 = true;
    };
    const shujuhuitan = (row, checkAlltree) => {
      // 如果没有数据的话就添加数据
      if (!row.children) {
        return checkAlltree.push(row.id);
      }
      // 有数据的话 就遍历循环添加最后一项的id  item是下一层的row
      row.children.forEach((item) => {
        shujuhuitan(item, checkAlltree);
      });
    };
    // 点击分配权限的确定按钮
    const fpqx = async () => {
      console.log("获取", shujuAll);
      //   全部被选中的那一项;
      shujuAll.value.getCheckedKeys().forEach((item) => {
        obj.checkAlltree1.push(item);
      });
      shujuAll.value.getHalfCheckedKeys().forEach((item) => {
        obj.checkAlltree1.push(item);
      });
      // 把数组转为字符串
      const zhuanzfc = obj.checkAlltree1.join(",");
      // 调用角色授权的接口
      const res = await roleshouquan(obj.jueseid, zhuanzfc);
      obj.dialogFormVisible2 = false;
      getlist();
    };
    // 删除第一级
    const del1 = (id, rid, row) => {
      ElMessageBox.confirm("您确定要删除它吗?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        .then(async () => {
          const res = await deljues(id, rid);
          row.children = res;
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    // 删除第二级
    const del2 = (id, rid, row) => {
      ElMessageBox.confirm("您确定要删除它吗?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        .then(async () => {
          const res = await deljues(id, rid);
          row.children = res;
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    // 删除第三级
    const del3 = (id, rid, row) => {
      ElMessageBox.confirm("您确定要删除它吗?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        .then(async () => {
          const res = await deljues(id, rid);
          row.children = res;
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    return {
      ...toRefs(obj),
      edadd,
      add,
      adduser,
      qk,
      edit,
      xg,
      del,
      xuroles,
      fpqx,
      del1,
      del2,
      del3,
      shujuAll,
      Edit,
      Delete,
      Setting,
    };
  },
};
</script>
<style lang="scss" scoped>
.el-tag {
  margin: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
